<template>
    <div class="modify-teacher">
        <header class="modify-header">
            <div class="left">
                <span class="arrow" @click="$router.back()"><i class="el-icon-arrow-left" />返回</span>
                <span>|</span>
                <span>分组管理</span>
            </div>
            <div class="right">
                课程管理系统
            </div>
        </header>
        <main class="modify-main">
            <div class="form-container" style="line-height: 100px;text-align:center;">
                <div class="tableLab" style="text-align: right;">
                    <el-button type="primary" style="margin-left: 15px" @click="getCourseRecords()">
                        + 新建小组
                    </el-button>
                </div>
                <el-table :data="tableData" stripe class="data_table">
                    <el-table-column prop="courses.courseName" label="课程名称">
                    </el-table-column>
                    <el-table-column prop="id" label="组编号">
                    </el-table-column>
                    <el-table-column prop="leader" label="组长">
                    </el-table-column>
                    <el-table-column label="操作" align="center" style="width: 250px;">
                        <template slot-scope="scope">
                            <el-button type="text" size="small" class="blueBug"
                                @click="memberHandle(scope.row.id, scope.row.leader)">
                                成员
                            </el-button>
                            <el-button type="text" size="small" class="blueBug" @click="editHandle(scope.row.id)">
                                编辑
                            </el-button>
                            <el-button type="text" size="small" class="delBut" @click="deleteHandle(scope.row.id)">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 新建，修改弹窗 -->
            <el-dialog :title="action" :visible.sync="dialogVisible">
                <!-- 成绩表 -->
                <div class="score-table-container">
                    <el-table :data="RecordsList" stripe class="data_table">
                        <el-table-column prop="studentId" label="学生编号">
                        </el-table-column>
                        <el-table-column prop="students.studentNumber" label="学生学号">
                        </el-table-column>
                        <el-table-column prop="students.className" label="班级名称">
                        </el-table-column>
                        <el-table-column prop="students.studentName" label="学生姓名">
                        </el-table-column>
                        <el-table-column label="操作" width="150px" align="center">
                            <template slot-scope="scope">
                                <el-button type="text" size="small" class="blueBug"
                                    @click="leaderHandle(scope.row.courseId, scope.row.studentId, scope.row.students.studentName)">
                                    设为组长
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-dialog>
        </main>
    </div>
</template>

<script>
// import { getUserIDLocalStorage } from "@/utils/utilLocalStorage";
// import { isEmpty } from "@/utils/checkString";
// import { getInfoAPI_Teacher, modifyAPI_Teacher } from "@/api/teacher/personal";
import { getAllGroupsAPI, getGroupsAPI, addGroupsAPI, editGroupsAPI, deleteGroupsAPI } from "@/api/groups";
import { deleteMemberAPI, addMemberAPI } from "@/api/groupMember";
import { getCourseRecordsAPI } from '@/api/score'

export default {
    name: 'Groups',
    data() {
        return {
            allId: '',
            dialogVisible: false,
            courseId: '',
            tableData: [],
            RecordsList: [],
            // groupTableData: [],
            action: '新增组长姓名',
            rules: {
                leader: [
                    { required: true, message: '请输入小组长姓名', trigger: 'blur' },
                ],
            }
        }
    },
    mounted() {
        //接收跳转传过来的课程id
        this.courseId = this.$route.query.courseId
        this.getAllGroups()
    },
    methods: {
        //获取分组
        getAllGroups() {
            getAllGroupsAPI(this.courseId).then(res => {
                this.tableData = res.data
            })
        },
        //成员按钮
        memberHandle(groupId, leader) {
            let currentCourseId = this.courseId
            this.$router.push({ path: '/groupMemberships/getByGroupId', query: { groupId: groupId, leader: leader, courseId: currentCourseId } });
        },
        //学生成绩单
        //获取该课程所包含的所有成绩单
        async getCourseRecords() {
            this.dialogVisible = true
            getCourseRecordsAPI(this.courseId).then(res => {
                this.RecordsList = res.data
            })
        },
        //新建，编辑里的 设置组长按钮 (新增，修改方法)
        leaderHandle(courseId, studentId, leader) {
            //请求体 Body
            if (leader == null) {
                this.$message.error('小组长姓名不能为空')
                return false
            }
            let newData = {
                courseId: courseId,
                leader: leader,
                studentId: studentId
            }
            //新增,修改
            if (!this.allId) {
                addGroupsAPI(newData).then(res => {
                    if (res.code === 200) {
                        // 新增小组成功
                        this.getAllGroups()
                        // this.$message.success('新增小组成功！');
                        // this.dialogVisible = false;
                        // let newGroupId = this.tableData[this.tableData.length - 1].id
                        if (res.data.number === 1 && res.data.groupId !== null) {
                            let newGroupId = res.data.groupId
                            console.log('add' + newGroupId);
                            // 尝试添加组长到新组
                            this.addMember(newGroupId, studentId).then(() => {
                                // 如果组长添加成功，则继续
                                this.getAllGroups();
                                this.dialogVisible = false;
                            }).catch(error => {
                                // 如果组长添加失败，回滚小组添加操作
                                // this.rollbackGroupAddition(newGroupId);
                                this.dialogVisible = false;
                            });
                        } else if (res.data.successCode === 50003) {
                            this.$message.error('该学生已经在这门课程中创建过组，该学生不能再继续创建组')
                        } else if (res.data.successCode === 30006) {
                            this.$message.error('该学生已经在一门课程中加入到其它组中，该学生不能再继续创建组')
                        }
                    } else {
                        // 新增小组失败
                        this.$message.error('新增小组失败！');
                        this.dialogVisible = false;
                    }
                })
                // .catch(error => {
                //     // 处理错误情况
                //     console.error(error);
                //     // this.$message.error('新增小组出错');
                //     this.dialogVisible = false;
                // });
            } else {
                //TODO 修改时同leader也可以
                //修改 (Path:groupId , Boby: courseId,leader)
                editGroupsAPI(this.allId, newData).then(res => {
                    if (res.code === 200) {
                        this.$message.success('修改小组成功')
                        this.getAllGroups()
                    } else {
                        this.$message.error('修改小组失败')
                    }
                    this.allId = ''
                    this.dialogVisible = false
                }).catch((error) => {
                    console.log(error);
                })
            }
        },
        // //添加成员
        // addMember(groupId, studentId) {
        //     addMemberAPI(groupId, studentId).then((res) => {
        //         if (res.code === 200) {
        //             // this.$message.success('添加成员成功')
        //             if (res.data === 30011) {
        //                 this.$message.error('组长添加失败，该组长已加入其他组')
        //             }
        //         } else {
        //             this.$message.error('添加成员失败')
        //         }
        //         this.dialogVisible = false
        //         this.getGroupMembers()
        //     }).catch((error) => {
        //         // console.log(error);
        //         this.$message.error('组长添加失败，该组长已加入其他组')
        //     })
        // },
        // 添加成员
        addMember(groupId, studentId) {
            return addMemberAPI(groupId, studentId).then((res) => {
                if (res.code === 200) {
                    // 添加成员成功
                    this.$message.success('添加成员成功');
                } else {
                    // 添加成员失败，抛出错误以便回滚小组添加操作
                    throw new Error('组长添加失败，该组长已加入其他组');
                }
                this.getGroupMembers();
            });
        },
        // 回滚小组添加操作
        rollbackGroupAddition(groupId) {
            // 假设有一个删除小组的API
            deleteMemberAPI(groupId).then(res => {
                if (res.code === 200) {
                    this.$message.error('由于组长已加入其他组，新增小组已回滚');
                } else {
                    this.$message.error('回滚小组添加操作失败');
                }
            }).catch(error => {
                console.error(error);
                this.$message.error('回滚小组添加操作出错');
            });
        },
        //编辑按钮
        editHandle(groupId) {
            this.action = '修改组长姓名'
            this.dialogVisible = true
            this.getCourseRecords()
            this.allId = groupId // 将组id存入全局             
            // getGroupsAPI(groupId).then(res => {
            //     this.groupTableData = res.data
            // })
        },
        //删除组按钮(整组删除)
        deleteHandle(groupId) {
            //删除组长
            this.$confirm('删除即解散小组！！！确认删除该组, 是否继续?', '确定删除', {
                confirmButtonText: '删除',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.deleteGroups(groupId)
            })
        },
        //删除组方法
        deleteGroups(groupId) {
            deleteGroupsAPI(groupId).then(res => {
                if (res.code == 200) {
                    this.$message.success('删除小组成功！')
                } else {
                    this.$message.error('删除小组失败！')
                }
                this.getAllGroups()
            }).catch(() => {
                this.$message.console.error('删除小组失败！');
            })
        }
    }
}
</script>

<style scoped lang="scss">
.modify-teacher {
    background-color: #f4f6f8;
    height: 100vh;

    .modify-header {
        display: flex;
        justify-content: space-between;
        padding: 0 20px;
        height: 64px;
        line-height: 64px;
        font-size: 16px;
        font-weight: bold;
        background-color: #fff;

        .left {
            span {
                margin-right: 4px;
            }

            .arrow {
                cursor: pointer;
            }
        }

        .right {
            text-align: right;
        }
    }

    .modify-main {
        background: #f4f6f8;
        padding: 20px 130px;

        .form-container {
            background-color: #fff;
            padding-left: 300px;
            padding-right: 300px;
            padding-bottom: 100px;

            .title {
                height: 60px;
                line-height: 60px;
                padding-left: 20px;
            }

            .form {
                margin-bottom: 20px;
                padding: 20px 65px 24px;

                .el-form {
                    display: flex;
                    flex-wrap: wrap;

                    .el-form-item {
                        width: 50%;
                    }
                }
            }
        }
    }

    .modify-footer {
        position: fixed;
        bottom: 10px;
        width: 100%;
        padding: 30px 50px;
        color: #000000d9;
        font-size: 18px;
        background: #fff;
        text-align: center;
    }

    // 头像上传
    .avatar-uploader .el-upload {
        border: 1px dashed #bd2525;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #4770a9;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }

    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
}
</style>